<?php

namespace app\server;

use \think\facade\Db;
use think\facade\Request;
use think\facade\Cache;
use think\facade\Queue;

class BaiduServer
{
    public function getBdToken()
    {
        $token = '';
        $tokenKey = 'bdToken';
        if (!empty(cache($tokenKey))) {
            return cache($tokenKey);
        }
        $url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' . config('baidu.api_key') . '&client_secret=' . config('baidu.api_secret') . '&';
        $response = file_get_contents($url);
        $arr = json_decode($response, true);
        if (isset($arr['access_token'])) {
            $token = $arr['access_token'];
            cache($tokenKey, $token, 3600 * 24 * 29);
        }
        return $token;
    }

    /**
     * 制作音频任务
     * @param $storyId
     * @param $text
     */
    public function getVideo($storyId, $text,$videoType)
    {
        $accessToken = $this->getBdToken();
        $url = 'https://aip.baidubce.com/rpc/2.0/tts/v1/create?access_token=' . $accessToken;
        $text = strip_tags($text);
        $replaceArr = [
            '&rdquo;'=>'',
            '&hellip;'=>'',
            '&ldquo;'=>'',
            '&middot;'=>'',
            '&mdash;'=>'',

        ];
        $text = str_replace(array_keys($replaceArr),array_values($replaceArr),$text);
        $data = [
            'text' => $text,
            'format' => 'mp3-16k',
            'voice' => $videoType,
            'lang' => 'zh',
            'speed' => 4
        ];
//        var_dump($text); die();
        $response = curlData($url, json_encode($data), 'POST');
        var_dump($response); die();
        $arr = json_decode($response, true);
        if (isset($arr['task_id'])) {
            add('app_whale_story_video', ['story_id' => $storyId, 'task_id' => $arr['task_id']]);
        }
    }

    /**
     * 获取音频地址
     * @param $taskId
     */
    public function getVideoUrl($taskId)
    {
        $accessToken = $this->getBdToken();
        $url = 'https://aip.baidubce.com/rpc/2.0/tts/v1/query?access_token=' . $accessToken;
        $data = [
            'task_ids' => [$taskId],
        ];
        $response = curlData($url, json_encode($data), 'POST');
        var_dump($response);
        $speech_url = '';
        $arr = json_decode($response, true);
        if (!empty($arr['tasks_info'])) {
            foreach ($arr['tasks_info'] as $value) {
                if($value['task_status'] == 'Success'){
                    $speech_url = $value['task_result']['speech_url'];
                    edit('app_whale_story_video',['task_id'=>$taskId],['video_url'=>$speech_url]);
                }
            }
        }
        var_dump($taskId);
        return $speech_url;
    }


}


?>